<?php

namespace app\data\service;

use think\admin\Service;

/**
 * 产品数据服务
 * Class GoodsService
 * @package app\data\service
 */
class GoodsService extends Service
{


    public function getInfo($id){
        return $this->app->db->name('ShopGoods')->where('id', $id)->find();
    }

    /**
     * 获取公司数据
     * @return array
     */
    public function getCompanyData(): array
    {
        $map = ['status' => 1];
        $query = $this->app->db->name('ShopGoodsCompany');
        return $query->where($map)->order('sort desc,id desc')->column('id,name', 'id');
    }

    /**根据公司ID获取分类数据
     * @param $company_id
     * @return array
     */
    public function getCateDataByCompanyId($company_id){
        $map = ['status' => 1, 'deleted' => 0, 'company_id' => $company_id];
        return $this->app->db->name('ShopGoodsCate')->where($map)->column('id,name,company_id', 'id');
    }

    /**
     * 获取分类数据
     * @return array
     */
    public function getCateData(): array
    {
        $map = ['status' => 1];
        return $this->app->db->name('ShopGoodsCate')->where($map)->column('id,name,company_id', 'id');
    }

    /**
     * 更新产品库存数据
     * @param string $code
     * @return boolean
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function stock(string $code): bool
    {
        // 产品入库统计
        $query = $this->app->db->name('ShopGoodsStock');
        $query->field('goods_code,goods_spec,ifnull(sum(goods_stock),0) stock_total');
        $stockList = $query->where(['goods_code' => $code])->group('goods_code,goods_spec')->select()->toArray();
        // 产品销量统计
        $query = $this->app->db->table('shop_order a')->field('b.goods_code,b.goods_spec,ifnull(sum(b.stock_sales),0) stock_sales');
        $query->leftJoin('shop_order_item b', 'a.order_no=b.order_no')->where("b.goods_code='{$code}' and a.status>0 and a.deleted_status<1");
        $salesList = $query->group('b.goods_code,b.goods_spec')->select()->toArray();
        // 组装更新数据
        $dataList = [];
        foreach (array_merge($stockList, $salesList) as $vo) {
            $key = "{$vo['goods_code']}@@{$vo['goods_spec']}";
            $dataList[$key] = isset($dataList[$key]) ? array_merge($dataList[$key], $vo) : $vo;
            if (empty($dataList[$key]['stock_sales'])) $dataList[$key]['stock_sales'] = 0;
            if (empty($dataList[$key]['stock_total'])) $dataList[$key]['stock_total'] = 0;
        }
        unset($salesList, $stockList);
        // 更新产品规格销量及库存
        foreach ($dataList as $vo) {
            $map = ['goods_code' => $code, 'goods_spec' => $vo['goods_spec']];
            $set = ['stock_total' => $vo['stock_total'], 'stock_sales' => $vo['stock_sales']];
            $this->app->db->name('ShopGoodsItem')->where($map)->update($set);
        }
        // 更新产品主体销量及库存
        $this->app->db->name('ShopGoods')->where(['code' => $code])->update([
            'stock_total'   => intval(array_sum(array_column($dataList, 'stock_total'))),
            'stock_sales'   => intval(array_sum(array_column($dataList, 'stock_sales'))),
            'stock_virtual' => $this->app->db->name('ShopGoodsItem')->where(['goods_code' => $code])->sum('number_virtual'),
        ]);
        return true;
    }

    /**
     * 产品数据绑定
     * @param array $data 产品主数据
     * @param boolean $simple 简化数据
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function bindData(array &$data = [], $simple = true): array
    {
        $cates = $this->getCateData();
        $companys = $this->getCompanyData();
        foreach ($data as &$vo) {
            foreach ($cates as $cate) if ($cate['id'] == $vo['cate_id']) $vo['cateinfo'] = $cate;
            foreach ($companys as $company) if ($company['id'] == $vo['company_id']) $vo['companyinfo'] = $company;
            if ($simple) unset($vo['sort'], $vo['status'], $vo['deleted']);
        }
        return $data;
    }


    /**
     * @param array $where
     * @return \think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGoods($where = []){

        $whereBase[] = ['sg.deleted', '=', 0];

        $data = $this->app->db->name('ShopGoods')->alias('sg')
            ->leftJoin('shop_goods_cate sc', 'sc.id=sg.cate_id')
            ->leftJoin('shop_goods_company gc', 'gc.id=sg.company_id')
            ->field('sg.*, sc.name as cate_name, gc.name as company_name')
            ->where($where)->where($whereBase)->order('id desc')->select();

        return $data;
    }

}